package com.sample.library.portlet.category;

import javax.portlet.ActionRequest;
import javax.portlet.ActionResponse;
import javax.portlet.RenderRequest;

import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.portlet.bind.annotation.ActionMapping;

import com.sample.library.model.Category;
import com.sample.library.model.impl.CategoryImpl;
import com.sample.library.service.CategoryLocalServiceUtil;

@Controller
@RequestMapping("view")
public class EditCategoryController {
	
	@RequestMapping(params="action=editCategory")
	public String showEditCategory(Model model, RenderRequest request) {
		System.out.println("showEditCategory");
		Category category = new CategoryImpl();
		try{
			String categoryId = request.getParameter("categoryId");
			System.out.println("CategoryId:"+categoryId);
			category = CategoryLocalServiceUtil.getCategory(Long.valueOf(categoryId));
		} catch(Exception e) {
			System.out.println("getCategory is null");
		}
		
		model.addAttribute("category", category) ;
		return "category/edit";
	}
	
	@ActionMapping(params="action=updateCategory")
	public void updateCategory(ActionRequest request, ActionResponse response) throws Exception {
		
		System.out.println("updateCategory");
		Category category = getCategoryFromRequest(request);
		CategoryLocalServiceUtil.addCategory(category);
		
		response.setRenderParameter("action", "viewCategory");
	}

	private Category getCategoryFromRequest(ActionRequest request) {

		Category category = new CategoryImpl();
		try{
			String categoryId = request.getParameter("categoryId");
			category = CategoryLocalServiceUtil.getCategory(Long.valueOf(categoryId));
		} catch(Exception e) {
			System.out.println("getCategory is null");
		}
		
		String name = request.getParameter("name");
		String description = request.getParameter("description");
		category.setName(name);
		category.setDescription(description);
		
		return category;
	}
	
}
